package com.xiaoxi.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoxi.yygh.cmn.listener.DictListener;
import com.xiaoxi.yygh.cmn.mapper.DictMapper;
import com.xiaoxi.yygh.cmn.service.DictService;
import com.xiaoxi.yygh.model.cmn.Dict;
import com.xiaoxi.yygh.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator") //第一次查询后添加缓存
    public List<Dict> findChildData(Long id) {
        LambdaQueryWrapper<Dict> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Dict::getParentId, id);
        List<Dict> dictList = baseMapper.selectList(lqw);

        for (Dict dict : dictList) {
            Long dictId = dict.getId();
            boolean idChild = isChildren(dictId);
            dict.setHasChildren(idChild);
        }
        return dictList;
    }

    // 导出数据字典
    @Override
    public void exportDictData(HttpServletResponse response) {
        // 设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = "dict";
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        List<Dict> dictList = baseMapper.selectList(null);

        List<DictEeVo> dictEeVoList = new ArrayList<>();

        for (Dict dict : dictList) {
            DictEeVo dictEeVo = new DictEeVo();
            BeanUtils.copyProperties(dict, dictEeVo);
            dictEeVoList.add(dictEeVo);
        }

        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("dict")
                    .doWrite(dictEeVoList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 导入数据字典
    @CacheEvict(value = "dict", allEntries=true)
    @Override
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper))
                    .sheet().doRead();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getDictName(String dictcode, String value) {
        // 如果 dictcode 为空，直接根据 value 查询
        if (StringUtils.isEmpty(dictcode)){
            LambdaQueryWrapper<Dict> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Dict::getValue, value);

            Dict dict = baseMapper.selectOne(lqw);
            return dict.getName();
        }else {
            // 如果 dictcode 不为空，根据 dictcode 与 value 查询
            // 根据 dictcode 查询 dict，得到dict的 id值
            LambdaQueryWrapper<Dict> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Dict::getDictCode, dictcode);
            Dict parent_dict = baseMapper.selectOne(lqw);
            Long parent_dictId = parent_dict.getId();
            
            //根据 parent_dictId 与 value 查询
            LambdaQueryWrapper<Dict> dictLqw = new LambdaQueryWrapper<>();
            dictLqw.eq(Dict::getId, parent_dictId).eq(Dict::getValue, value);

            Dict dict = baseMapper.selectOne(dictLqw);
            return dict.getName();
        }
    }

    private boolean isChildren(Long id) {

        LambdaQueryWrapper<Dict> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Dict::getId, id);

        Integer count = baseMapper.selectCount(lqw);
        return count > 0;
    }
}
